<template>
  <div class="favorite-container">
    <!-- 返回按钮 -->
    <div v-if="showContent" class="back-button">
      <el-button @click="showContent = false">
        <t-icon name="arrow-left" /> 返回
      </el-button>
    </div>
  </div>  
    <!-- 内容展示区域 -->
    <div v-if="showContent" class="content-section">
      <h2 class="section-title">
        <t-icon name="folder" class="title-icon" />
        {{ currentFolder.folderName }}
      </h2>
      
      <div v-if="contents.length === 0" class="empty-content animate__animated animate__fadeIn">
        <t-icon name="file-unknown" class="empty-icon" />
        <p>该收藏夹暂无内容</p>
      </div>
      
      <div v-else class="content-grid">
        <div 
          v-for="content in contents" 
          :key="content.id" 
          class="content-item animate__animated animate__fadeIn"
          :class="getContentClass(content.contentType)"
        >
          <div class="content-type-badge">
            <t-icon :name="getContentIcon(content.contentType)" />
            <span>{{ getContentTypeName(content.contentType) }}</span>
          </div>
          
          <div v-if="content.contentType === 'article'" class="content-preview">
            <h3 class="content-title" @click="navigateToContent(content)">
              {{ content.content.title }}
            </h3>
            <p class="content-description">{{ content.content.description }}</p>
            <div class="content-meta">
              <span class="meta-item">
                <t-icon name="time" />
                {{ formatTime(content.content.createdAt) }}
              </span>
              <span class="meta-item">
                <t-icon name="thumb-up" />
                {{ content.content.likeCount || 0 }}
              </span>
              <span class="meta-item">
                <t-icon name="view" />
                {{ content.content.viewCount || 0 }}
              </span>
            </div>
          </div>
          
          <div v-if="content.contentType === 'question'" class="content-preview">
            <h3 class="content-title" @click="navigateToContent(content)">
              {{ content.content.title }}
            </h3>
            <p class="content-description" v-html="content.content.content"></p>
            <div class="content-meta">
              <span class="meta-item">
                <t-icon name="time" />
                {{ formatTime(content.content.createdAt) }}
              </span>
              <span class="meta-item">
                <t-icon name="chat" />
                {{ content.content.answerCount || 0 }}
              </span>
            </div>
          </div>
          
          <div v-if="content.contentType === 'answer'" class="content-preview">
            <p class="content-description">{{ content.content.content }}</p>
            <div class="content-meta">
              <span class="meta-item">
                <t-icon name="time" />
                {{ formatTime(content.content.createdAt) }}
              </span>
              <span class="meta-item">
                <t-icon name="thumb-up" />
                {{ content.content.likeCount || 0 }}
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>
  <div v-else class="favorite-container">
    <h2 class="section-title animate__animated animate__fadeIn">
      <t-icon name="star" class="title-icon" />
      我的收藏夹
    </h2>
    
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="3" animated />
    </div>
    
    <div v-else-if="favoriteFolders.length === 0" class="empty-state animate__animated animate__fadeIn">
      <t-icon name="info-circle" class="empty-icon" />
      <p>暂无收藏夹</p>
      <el-button type="primary" @click="showCreateFolderDialog" class="create-button">
        <t-icon name="plus" />
        创建收藏夹
      </el-button>
    </div>
    
    <div v-else class="favorite-content">
      <div class="folder-actions">
        <el-button type="primary" @click="showCreateFolderDialog" class="create-button">
          <t-icon name="plus" />
          创建收藏夹
        </el-button>
      </div>
      
      <div class="folder-list">
        <div 
          v-for="folder in favoriteFolders" 
          :key="folder.id" 
          class="folder-item animate__animated animate__fadeIn"
        >
          <div class="folder-header">
            <div class="folder-icon">
              <t-icon name="folder" />
            </div>
            <div class="folder-info">
              <h3 class="folder-name" 
                  @click="handleFolderClick(folder)"
                  :style="{ cursor: 'pointer' }">
                  {{ folder.folderName }}
              </h3>
              <div class="folder-meta">
                <span class="folder-count">
                  <t-icon name="file" />
                  {{ folder.contentCount || 0 }} 个内容
                </span>
                <span class="folder-time">创建于 {{ formatTime(folder.createdAt) }}</span>
              </div>
            </div>
          </div>
          
          <div class="folder-actions">
            <el-button 
              type="danger" 
              size="small" 
              @click="confirmDeleteFolder(folder)"
              class="delete-button"
            >
              <t-icon name="delete" />
              删除
            </el-button>
          </div>
        </div>
      </div>
      
      <el-pagination
        v-if="total > pageSize"
        background
        layout="prev, pager, next"
        :total="total"
        :page-size="pageSize"
        :current-page="currentPage"
        @current-change="handlePageChange"
        class="pagination"
      />
    </div>
    
    <!-- 创建收藏夹对话框 -->
    <el-dialog
      v-model="createFolderDialogVisible"
      title="创建收藏夹"
      width="30%"
      center
    >
      <el-form :model="newFolder" label-width="80px">
        <el-form-item label="名称">
          <el-input v-model="newFolder.folderName" placeholder="请输入收藏夹名称"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="createFolderDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="createFolder" :disabled="!newFolder.folderName">
            创建
          </el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 删除确认对话框 -->
    <el-dialog
      v-model="deleteConfirmVisible"
      title="确认删除"
      width="30%"
      center
    >
      <p>确定要删除收藏夹 "{{ folderToDelete?.folderName }}" 吗？此操作不可恢复。</p>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteConfirmVisible = false">取消</el-button>
          <el-button type="danger" @click="deleteFolder">
            确认删除
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { getAllFavoriteFoldersByUserId, createFavoriteFolder, deleteFavoriteFolder } from '@/api/favoriteFolder';
import { useUserStore } from '@/stores/userStore';
import { storeToRefs } from 'pinia';
import { getFavoriteContent } from '@/api/userApi';

const route = useRoute();
const router = useRouter();
const userStore = useUserStore();
const { profile } = storeToRefs(userStore);

const favoriteFolders = ref([]);
const loading = ref(true);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const showContent = ref(false);
const currentFolder = ref(null);
const contents = ref([]);
// 创建收藏夹相关
const createFolderDialogVisible = ref(false);
const newFolder = ref({
  folderName: ''
});

// 删除收藏夹相关
const deleteConfirmVisible = ref(false);
const folderToDelete = ref(null);

onMounted(() => {
  fetchFavoriteFolders();
});

// 监听路由参数变化
watch(
  () => route.params.id,
  (newId, oldId) => {
    if (newId && newId !== oldId) {
      currentPage.value = 1; // 重置页码
      fetchFavoriteFolders();
    }
  }
);

const fetchFavoriteFolders = async () => {
  loading.value = true;
  try {
    const userId = route.params.id;
    if (!userId) {
      ElMessage.warning('用户ID不存在');
      return;
    }
    
    const response = await getAllFavoriteFoldersByUserId(userId);
    if (response.code === 200) {
      favoriteFolders.value = response.data || [];
      total.value = favoriteFolders.value.length;
    } else {
      ElMessage.error(response.message || '获取收藏夹失败');
    }
  } catch (error) {
    console.error('获取收藏夹出错:', error);
    ElMessage.error('获取收藏夹失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

const handlePageChange = (page) => {
  currentPage.value = page;
  // 如果需要分页获取数据，这里可以调用fetchFavoriteFolders
};

const showCreateFolderDialog = () => {
  // 检查是否是当前用户
  if (profile.value.id !== Number(route.params.id)) {
    ElMessage.warning('只能在自己的主页创建收藏夹');
    return;
  }
  
  newFolder.value.folderName = '';
  createFolderDialogVisible.value = true;
};

const createFolder = async () => {
  try {
    if (!newFolder.value.folderName.trim()) {
      ElMessage.warning('收藏夹名称不能为空');
      return;
    }
    
    const data = {
      userId: profile.value.id,
      folderName: newFolder.value.folderName
    };
    
    const response = await createFavoriteFolder(data);
    if (response.code === 200) {
      ElMessage.success('创建收藏夹成功');
      createFolderDialogVisible.value = false;
      fetchFavoriteFolders(); // 重新获取收藏夹列表
    } else {
      ElMessage.error(response.message || '创建收藏夹失败');
    }
  } catch (error) {
    console.error('创建收藏夹出错:', error);
    ElMessage.error('创建收藏夹失败，请稍后重试');
  }
};

const confirmDeleteFolder = (folder) => {
  // 检查是否是当前用户
  if (profile.value.id !== Number(route.params.id)) {
    ElMessage.warning('只能删除自己的收藏夹');
    return;
  }
  
  folderToDelete.value = folder;
  deleteConfirmVisible.value = true;
};

const deleteFolder = async () => {
  try {
    if (!folderToDelete.value) return;
    
    const data = {
      userId: profile.value.id,
      folderName: folderToDelete.value.folderName
    };
    
    const response = await deleteFavoriteFolder(data);
    if (response.code === 200) {
      ElMessage.success('删除收藏夹成功');
      deleteConfirmVisible.value = false;
      fetchFavoriteFolders(); // 重新获取收藏夹列表
    } else {
      ElMessage.error(response.message || '删除收藏夹失败');
    }
  } catch (error) {
    console.error('删除收藏夹出错:', error);
    ElMessage.error('删除收藏夹失败，请稍后重试');
  }
};

const formatTime = (timeString) => {
  if (!timeString) return '';
  
  const date = new Date(timeString);
  const now = new Date();
  const diffMs = now - date;
  const diffSec = Math.floor(diffMs / 1000);
  const diffMin = Math.floor(diffSec / 60);
  const diffHour = Math.floor(diffMin / 60);
  const diffDay = Math.floor(diffHour / 24);
  
  if (diffDay > 30) {
    return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
  } else if (diffDay > 0) {
    return `${diffDay}天前`;
  } else if (diffHour > 0) {
    return `${diffHour}小时前`;
  } else if (diffMin > 0) {
    return `${diffMin}分钟前`;
  } else {
    return '刚刚';
  }
};

const handleFolderClick = async (folder) => {
  currentFolder.value = folder;
  showContent.value = true;
  try {
    const response = await getFavoriteContent(
      route.params.id,
      folder.id,
      1,
      10
    );
    contents.value = response.data;
  } catch (error) {
    console.error('加载内容失败:', error);
    ElMessage.error('加载内容失败，请稍后重试');
  }
};

// 获取内容类型对应的图标
const getContentIcon = (contentType) => {
  switch (contentType) {
    case 'article':
      return 'book';
    case 'question':
      return 'help';
    case 'answer':
      return 'message';
    default:
      return 'file';
  }
};

// 获取内容类型的中文名称
const getContentTypeName = (contentType) => {
  switch (contentType) {
    case 'article':
      return '文章';
    case 'question':
      return '问题';
    case 'answer':
      return '回答';
    default:
      return '内容';
  }
};

// 获取内容类型对应的CSS类名
const getContentClass = (contentType) => {
  return `${contentType}-item`;
};

// 导航到内容详情页
const navigateToContent = (content) => {
  router.push(`/home/${content.contentType}/${content.content.id}`);
};
</script>

<style scoped>
.favorite-container {
  padding: 20px;
  max-width: 900px;
  margin: 0 auto;
}

.section-title {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
  color: #333;
  font-size: 1.5rem;
}

.title-icon {
  margin-right: 10px;
  color: #ffc107;
}

.loading-container {
  padding: 20px;
  background: #f9f9f9;
  border-radius: 8px;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px;
  background: #f9f9f9;
  border-radius: 8px;
  color: #999;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.folder-actions {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 16px;
}

.create-button {
  display: flex;
  align-items: center;
}

.create-button .t-icon {
  margin-right: 4px;
}

.folder-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.folder-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-radius: 8px;
  background: #fff;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  transition: transform 0.2s, box-shadow 0.2s;
  border-left: 4px solid #ffc107;
}

.folder-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.folder-header {
  display: flex;
  align-items: center;
}

.folder-icon {
  font-size: 24px;
  color: #ffc107;
  margin-right: 16px;
}

.folder-name {
  margin: 0 0 8px 0;
  font-size: 1.2rem;
  color: #333;
}

.folder-meta {
  display: flex;
  gap: 16px;
  color: #666;
  font-size: 0.9rem;
}

.folder-count {
  display: flex;
  align-items: center;
}

.folder-count .t-icon {
  margin-right: 4px;
}

.folder-time {
  color: #999;
}

.delete-button {
  display: flex;
  align-items: center;
}

.delete-button .t-icon {
  margin-right: 4px;
}

.pagination {
  margin-top: 24px;
  display: flex;
  justify-content: center;
}

@media (max-width: 768px) {
  .favorite-container {
    padding: 12px;
  }
  
  .folder-item {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .folder-actions {
    margin-top: 12px;
    align-self: flex-end;
  }
}

.back-button {
  margin-bottom: 20px;
}

.content-section {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.05);
}

.content-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.content-item {
  position: relative;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.08);
  transition: transform 0.2s, box-shadow 0.2s;
  overflow: hidden;
}

.content-item:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0,0,0,0.12);
}

.article-item {
  border-top: 4px solid #42b983;
  background: linear-gradient(to bottom, rgba(66, 185, 131, 0.05), transparent);
}

.question-item {
  border-top: 4px solid #2d8cf0;
  background: linear-gradient(to bottom, rgba(45, 140, 240, 0.05), transparent);
}

.answer-item {
  border-top: 4px solid #ff9900;
  background: linear-gradient(to bottom, rgba(255, 153, 0, 0.05), transparent);
}

.content-type-badge {
  position: absolute;
  top: 10px;
  right: 10px;
  display: flex;
  align-items: center;
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 0.8rem;
  color: white;
  background: rgba(0, 0, 0, 0.6);
}

.content-type-badge .t-icon {
  margin-right: 4px;
}

.content-preview {
  margin-top: 10px;
}

.content-title {
  font-size: 1.1rem;
  margin-bottom: 10px;
  color: #333;
  cursor: pointer;
  transition: color 0.2s;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.content-title:hover {
  color: #0056b3;
  text-decoration: underline;
}

.content-description {
  color: #666;
  font-size: 0.9rem;
  margin-bottom: 12px;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.content-meta {
  display: flex;
  gap: 12px;
  color: #999;
  font-size: 0.8rem;
}

.meta-item {
  display: flex;
  align-items: center;
}

.meta-item .t-icon {
  margin-right: 4px;
}

.empty-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px;
  color: #999;
}

.empty-content .empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
  color: #ddd;
}
</style>
